// docs: https://moonofweisheng.github.io/uni-mini-router/
import { createRouter } from 'uni-mini-router';
import type { Router } from 'uni-mini-router';

// 导入pages.json
import pagesJson from '../pages.json';
// 引入uni-parse-pages
import pagesJsonToRoutes from 'uni-parse-pages';
// 生成路由表
const routes = pagesJsonToRoutes(pagesJson);
const router: Router = createRouter({
  routes: [...routes] // 路由表信息
});

const routerPush = router.push;

const { VITE_OPEN_SUB_MINI } = import.meta.env;

/**
 * 重写 router.push 方法
 * 如果当前路由是 tabBar 路由，改为pushTab 跳转
 */
const redirectRouter = () => {
  const tabBarPath = pagesJson.tabBar.list.map((item: any) => item.pagePath);
  const tabBarList = pagesJson.pages
    .filter((item: any) => tabBarPath.includes(item.path))
    .map((item: any) => ({
      name: item.name,
      path: item.path
    }));

  router.push = function (...args) {
    const location = args[0] as any;

    const currentTabBar = tabBarList.find((item: any) => item.path === location?.url || item.name === location?.name);
    if (currentTabBar) {
      router.pushTab({ name: currentTabBar.name });
    }
    routerPush.apply(this, args);
  };
};

// 是否开启子包单独打包小程序
if (VITE_OPEN_SUB_MINI === 'true') {
  redirectRouter();
}

export default router;
export * from './interceptors';
export * from './white-list';
